package com.zzj.until;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.Properties;

public class DBTool {
	public static Statement stm;
	public static ResultSet ret;
	private static Connection con;
	
	
	private DBTool() {
	}
	static { 
		try {
			Class.forName("oracle.jdbc.driver.OracleDriver");
		}catch(Exception e) {
			e.printStackTrace(); 
		}
	}
	
	private static Statement getstm(){
		if(stm == null){
			try {
				stm=getConn().createStatement();
			} catch (SQLException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		
		return stm;
	}
	
	/**
	 * 获取数据库链接 
	 * @return
	 * @throws SQLException 
	 */ 
	public static Connection getConn() throws SQLException{
		if(con != null){
			return con;
		}
		Properties jdbcproper = getPprVue("config/jdbc.properties");
		String dbip = jdbcproper.getProperty("dbip");  //数据库IP地址
		String dbserver = jdbcproper.getProperty("dbserver");  //实例名
		//String instance = jdbcproper.getProperty("instance");  //实例名
		String dbport = jdbcproper.getProperty("dbpost");  //端口号
		String dbuser = jdbcproper.getProperty("dbuser");  //用户名
		String dbpass = jdbcproper.getProperty("dbpass");  //密码
		String url = jdbcproper.getProperty("dburl");  //密码
		if(url == null || "".equals(url)){
			url="jdbc:oracle:thin:@"+dbip+":"+dbport+":"+dbserver;
		}
			//System.out.print(">>>>>>>"+url);
			return DriverManager.getConnection(url, dbuser, dbpass);
		
	}
	/**
	 * 获取配置文件          
	 * @param properName
	 * @return
	 */
	public static Properties getPprVue(String properName) {
		Properties p = new Properties();           
		try {       
			InputStream inputStream = new BufferedInputStream(new FileInputStream(properName));
			p.load(inputStream);       
			inputStream.close();      
		} catch (IOException e) {      
			e.printStackTrace();      
		}           
		return p;          
	}
	
	
	public static void free(ResultSet rs,Statement st,Connection con) {
		try {
			if(rs != null) {
				rs.close();
			}
		}catch(Exception e) {
			e.printStackTrace();
		}finally {
			try {
				if(st != null) {
					st.close();
				}
			}catch(Exception e) {
				e.printStackTrace();
			}finally {
				try {
					if(con != null) {
						con.close();
					}
				}catch(Exception e) {
					e.printStackTrace();
				}
			}
		}
	}
	
	
}
